import axios, {
  AxiosInstance,
  InternalAxiosRequestConfig,
  AxiosResponse,
} from "axios";
import { message, notification } from "ant-design-vue";
import { getToken, removeToken, removeUser } from "@/utils/Auth";
import router from "@/router/index.js";

// 创建通知容器实例
const [api, contextHolder] = notification.useNotification();

interface ResponseData<T = any> {
  code: number;
  data: T;
  message: string;
}

const request: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 1000 * 60 * 3,
  headers: {
    "Content-Type": "application/json;charset=utf-8", // 设置请求头中的Content-Type
  },
});

request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加token等
    const token = getToken();
    if (token) {
      config.headers["Authorization"] = token;
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  },
);

request.interceptors.response.use(
  (response: AxiosResponse<ResponseData>) => {
    const res = response.data;
    if (res.code === 401) {
      api.info({
        message: "登录失效，请重新登录",
        description: "即将返回登录页重新登录！",
      });
      // 跳转到登录页面
      router.replace({ name: "login" });
      // 清除存储的 Token 和用户信息
      removeToken();
      removeUser();
    }
    if (res.code !== 200) {
      message.error(res.message || "Error");
      return Promise.reject(new Error(res.message || "Error"));
    }
    return res.data;
  },
  (error: any) => {
    message.error(error.message || "Error");
    return Promise.reject(error);
  },
);

export default request;
